package cn.dev33.satoken.dao.mapper;

import cn.dev33.satoken.dao.entity.SaTokenData;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

import java.util.List;
import java.util.stream.Collectors;

/**
 * sa_token_data Mapper
 *
 * @author moon69
 * @since 1.37.0
 */
public interface SaTokenDataMapper extends BaseMapper<SaTokenData> {

    /**
     * select * from sa_token_data where token_key = tokenKey
     *
     * @param tokenKey 键
     * @return SaTokenData
     */
    default SaTokenData findByTokenKey(String tokenKey) {
        LambdaQueryWrapper<SaTokenData> wrapper = new LambdaQueryWrapper<SaTokenData>()
                .eq(SaTokenData::getTokenKey, tokenKey);
        return this.selectOne(wrapper);
    }

    /**
     * select token_key from where token_key like 'prefix%' and token_key like '%keyword%'
     *
     * @param prefix  前缀
     * @param keyword 关键字
     * @return 查询到的数据集合
     */
    default List<String> findKeyList(String prefix, String keyword) {
        LambdaQueryWrapper<SaTokenData> wrapper = new LambdaQueryWrapper<SaTokenData>()
                .select(SaTokenData::getTokenKey)
                .likeRight(SaTokenData::getTokenKey, prefix)
                .like(SaTokenData::getTokenKey, keyword);
        return this.selectList(wrapper)
                .stream()
                .map(SaTokenData::getTokenKey)
                .collect(Collectors.toList());
    }

    /**
     * delete from sa_token_data where token_key = tokenKey
     *
     * @param tokenKey 键
     */
    default void deleteByTokenKey(String tokenKey) {
        LambdaQueryWrapper<SaTokenData> wrapper = new LambdaQueryWrapper<SaTokenData>()
                .eq(SaTokenData::getTokenKey, tokenKey);
        this.delete(wrapper);
    }

    /**
     * delete from sa_token_data where expire_time > leftTime and expire_time < rightTime
     *
     * @param leftTime  大于的时间戳
     * @param rightTime 小于的时间戳
     */
    default void deleteByExpireTime(Long leftTime, Long rightTime) {
        LambdaQueryWrapper<SaTokenData> wrapper = new LambdaQueryWrapper<SaTokenData>()
                .gt(SaTokenData::getExpireTime, leftTime)
                .lt(SaTokenData::getExpireTime, rightTime);
        this.delete(wrapper);
    }

    /**
     * update sa_token_data set expire_time = expireTime where token_key = tokenKey
     *
     * @param tokenKey   键
     * @param expireTime 过期时间
     */
    default void updateExpireTime(String tokenKey, Long expireTime) {
        LambdaUpdateWrapper<SaTokenData> wrapper = new LambdaUpdateWrapper<SaTokenData>()
                .set(SaTokenData::getExpireTime, expireTime)
                .eq(SaTokenData::getTokenKey, tokenKey);
        this.update(null, wrapper);
    }

}
